package com.itheima.reggie.handler;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.CustomException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//异常处理类
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    //处理主键唯一
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultInfo HandlerDuplicateKeyException(Exception e) {
        //打印一下
        e.printStackTrace();
        if (e.getMessage().contains("idx_category_name")) {
            return ResultInfo.error("分类名称冲突");
        }
        //返回一个结果给前端
        return ResultInfo.error("添加的值重复了，请换个名字");
    }

    //自定义异常
    @ExceptionHandler(CustomException.class)
    public ResultInfo HandlerCustomException(Exception e) {
        //打印
        e.printStackTrace();
        //返回一个结果给前端
        return ResultInfo.error(e.getMessage());
    }
    //非预期异常
    @ExceptionHandler(Exception.class)
    public ResultInfo HandlerException(Exception e) {
        //打印
        e.printStackTrace();
        //给前端一个假提示
        return ResultInfo.error("滚你妈🐎");
    }
}
